package com.qf.cloud2203.getcoupons.coupons.service.impl;


import cn.hutool.json.JSONUtil;
import cn.hutool.jwt.JWT;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.qf.cloud2203.domain.constants.Constants;
import com.qf.cloud2203.domain.entity.Coupon;
import com.qf.cloud2203.domain.entity.Users;
import com.qf.cloud2203.domain.vo.ResultVo;
import com.qf.cloud2203.getcoupons.coupons.mapper.UsersMapper;
import com.qf.cloud2203.getcoupons.coupons.service.UsersService;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SetOperations;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author ada
 * @since 2023-03-10
 */
@Service
public class UsersServiceImpl extends ServiceImpl<UsersMapper, Users> implements UsersService {
    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    RabbitTemplate rabbitTemplate;

    public Coupon getCoupon() throws JsonProcessingException {
        Coupon coupon = (Coupon) redisTemplate.opsForList().leftPop(Constants.COUPON_KEY);
        return coupon;
    }

    /**
     * 抢卷接口
     * 抢卷成功用mq给couponRecord里的消费者发送内容
     *
     * @param name
     * @param phone
     * @return
     * @throws JsonProcessingException
     */
    @Override
    public ResultVo gradCoupon(String name, String phone) throws Exception {
        Object redisToken = redisTemplate.opsForValue().get(phone);
        if (redisToken == null || redisToken.equals("")) {
            Coupon coupon = (Coupon) redisTemplate.opsForList().leftPop(Constants.COUPON_KEY);
            if (coupon == null) {
                throw new Exception("没有卷了");
            } else {
                ObjectMapper objectMapper = new ObjectMapper();
                String token = JWT.create().setPayload("phone", phone)
                        .setExpiresAt(new Date(System.currentTimeMillis() + 24 * 60 * 60 * 1000))
                        .setKey(Constants.SECRET.getBytes(StandardCharsets.UTF_8))
                        .sign();
                redisTemplate.opsForValue().set(phone, new Date(), 1, TimeUnit.DAYS);
                Users users = new Users();
                users.setCouponId(coupon.getCouponId());
                users.setUsername(name);
                users.setPhone(phone);
                String usersJson = objectMapper.writeValueAsString(users);
                rabbitTemplate.convertAndSend("coupon_exchange", "coupons.1.1", usersJson);
                return ResultVo.ok("抢卷成功");
            }
        }
        return ResultVo.error("今日已抢过优惠券");
    }
}
